package com.cm.stock.manager.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.cm.stock.manager.dto.FactureDTO;

@Transactional
public class FactureDAO {
	@PersistenceContext
	private EntityManager em;
	
	public FactureDTO get(Integer id){
		return em.find(FactureDTO.class, id);
	}
	
	public FactureDTO getByCode(String code){
		try{
			return (FactureDTO) em.createQuery("select f from FactureDTO f where f.code=:code")
					.setParameter("code", code).getSingleResult();
		}catch (NoResultException e) {
			return null;
		}
		
	}
	
	public int getMaxId(){
		try{
			return (Integer) em.createQuery("select max(f.id) from FactureDTO f ")
				.getSingleResult();
		}catch (Exception e) {
			return 0;
		}
	}
		
	public FactureDTO save(FactureDTO facture){
			em.persist(facture);
			return facture;
		}
		
	@SuppressWarnings("unchecked")
	public List<FactureDTO> getAll(){
		
		return em.createQuery("select f from FactureDTO f").getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<FactureDTO> getAllNonSolder(){
		
		return em.createQuery("select f from FactureDTO f where f.solde!=0").getResultList();
	}
	
	public FactureDTO update(FactureDTO facture){
		return em.merge(facture);
	}
	
public void deleteOne(Integer id) throws Exception {
		
		FactureDTO facture = em.find(FactureDTO.class, id);
		if(facture==null){
			throw new Exception("Facture inexistant!");
		}
		em.remove(facture);
	}

}
